/*
 * @lc app=leetcode.cn id=535 lang=typescript
 *
 * [535] TinyURL 的加密与解密
 */

// @lc code=start

// 存储短链接到长链接的映射关系
const hash: Map<string, string> = new Map();

// 小写字母、大写字母和数字随机字符
const randChar = (seed: number): string => {
  const base = ['a'.charCodeAt(0), 'A'.charCodeAt(0), '0'.charCodeAt(0)];
  const limit = (62 * seed) >> 0;
  if (limit < 26) {
    return String.fromCharCode(limit + base[0]);
  } else if (limit < 52) {
    return String.fromCharCode(limit - 26 - base[1]);
  } else {
    return String.fromCharCode(limit - 52 + base[2]);
  }
};

// 生成 n 长度的随机串
const randStr = (n: number): string => {
  let s = '';
  do {
    let seed = Math.random();
    s += randChar(seed);
  } while (n--);
  return s;
};
/**
 * Encodes a URL to a shortened URL.
 */
function encode(longUrl: string): string {
  let tinyUrl: string;
  do {
    tinyUrl = randStr(5);
  } while (hash.has(tinyUrl));

  hash.set(tinyUrl, longUrl);
  return tinyUrl;
}

/**
 * Decodes a shortened URL to its original URL.
 */
function decode(shortUrl: string): string {
  return hash.get(shortUrl);
}

/**
 * Your functions will be called as such:
 * decode(encode(strs));
 */
// @lc code=end
